import { Position, ChessUnit, EnemyUnit, GameSkills } from '../types/game';

// 技能类型
export type SkillType = 'fireAttack' | 'reinforcement' | 'inspire';

// 技能效果接口
interface SkillEffect {
  id: string;
  type: string;
  startTime: number;
  duration: number;
  position?: Position;
  radius?: number;
  damage?: number;
  onUpdate?: (progress: number) => void;
  onComplete?: () => void;
}

// 技能配置
interface SkillConfig {
  name: string;
  description: string;
  maxEnergy: number;
  cooldown: number; // 毫秒
  energyGainRate: number; // 每秒获得的能量
  manaCost?: number; // 棋魂消耗
}

// 技能配置数据
const SKILL_CONFIGS: Record<SkillType, SkillConfig> = {
  fireAttack: {
    name: '火攻',
    description: '对指定区域造成持续火焰伤害',
    maxEnergy: 100,
    cooldown: 30000, // 30秒
    energyGainRate: 2, // 每秒2点能量
    manaCost: 50
  },
  reinforcement: {
    name: '援军',
    description: '临时召唤锐士方阵阻挡敌人',
    maxEnergy: 80,
    cooldown: 45000, // 45秒
    energyGainRate: 1.5,
    manaCost: 30
  },
  inspire: {
    name: '激将',
    description: '提升全体友军攻击力和攻击速度',
    maxEnergy: 60,
    cooldown: 25000, // 25秒
    energyGainRate: 2.5,
    manaCost: 40
  }
};

// 技能系统类
export class SkillSystem {
  private skills: GameSkills;
  private activeEffects: SkillEffect[] = [];
  private lastUpdateTime: number = 0;
  private onChessSpiritChange: (amount: number) => void = () => {};
  private onCreateTempUnit: (position: Position, duration: number) => void = () => {};
  private onApplyUnitBuff: (buffType: string, duration: number) => void = () => {};

  constructor(
    initialSkills: GameSkills,
    callbacks: {
      onChessSpiritChange: (amount: number) => void;
      onCreateTempUnit: (position: Position, duration: number) => void;
      onApplyUnitBuff: (buffType: string, duration: number) => void;
    }
  ) {
    this.skills = { ...initialSkills };
    this.onChessSpiritChange = callbacks.onChessSpiritChange;
    this.onCreateTempUnit = callbacks.onCreateTempUnit;
    this.onApplyUnitBuff = callbacks.onApplyUnitBuff;
    this.lastUpdateTime = Date.now();
  }

  // 更新技能系统
  update(deltaTime: number): GameSkills {
    const currentTime = Date.now();
    const actualDeltaTime = currentTime - this.lastUpdateTime;
    this.lastUpdateTime = currentTime;

    // 更新能量积累
    this.updateEnergyGain(actualDeltaTime / 1000);

    // 更新冷却时间
    this.updateCooldowns(actualDeltaTime);

    // 更新技能效果
    this.updateSkillEffects(currentTime);

    return { ...this.skills };
  }

  // 更新能量积累
  private updateEnergyGain(deltaSeconds: number): void {
    Object.keys(this.skills).forEach(skillKey => {
      const skill = this.skills[skillKey as SkillType];
      const config = SKILL_CONFIGS[skillKey as SkillType];
      
      if (skill.energy < skill.maxEnergy) {
        const energyGain = config.energyGainRate * deltaSeconds;
        skill.energy = Math.min(skill.maxEnergy, skill.energy + energyGain);
      }
    });
  }

  // 更新冷却时间
  private updateCooldowns(deltaTime: number): void {
    Object.keys(this.skills).forEach(skillKey => {
      const skill = this.skills[skillKey as SkillType];
      
      if (skill.cooldown > 0) {
        skill.cooldown = Math.max(0, skill.cooldown - deltaTime);
      }
    });
  }

  // 更新技能效果
  private updateSkillEffects(currentTime: number): void {
    this.activeEffects = this.activeEffects.filter(effect => {
      const elapsed = currentTime - effect.startTime;
      const progress = Math.min(1, elapsed / effect.duration);
      
      // 更新效果
      if (effect.onUpdate) {
        effect.onUpdate(progress);
      }
      
      // 检查是否完成
      if (progress >= 1) {
        if (effect.onComplete) {
          effect.onComplete();
        }
        return false; // 移除效果
      }
      
      return true; // 保留效果
    });
  }

  // 使用技能
  useSkill(
    skillType: SkillType, 
    targetPosition?: Position, 
    currentChessSpirit: number = 0
  ): { success: boolean; message?: string } {
    const skill = this.skills[skillType];
    const config = SKILL_CONFIGS[skillType];
    
    // 检查能量是否足够
    if (skill.energy < skill.maxEnergy) {
      return { 
        success: false, 
        message: `${config.name}能量不足 (${Math.floor(skill.energy)}/${skill.maxEnergy})` 
      };
    }
    
    // 检查是否在冷却中
    if (skill.cooldown > 0) {
      return { 
        success: false, 
        message: `${config.name}冷却中 (${Math.ceil(skill.cooldown / 1000)}秒)` 
      };
    }
    
    // 检查棋魂是否足够
    if (config.manaCost && currentChessSpirit < config.manaCost) {
      return { 
        success: false, 
        message: `棋魂不足，需要${config.manaCost}点` 
      };
    }
    
    // 执行技能效果
    const effectResult = this.executeSkillEffect(skillType, targetPosition);
    
    if (effectResult.success) {
      // 消耗能量和棋魂
      skill.energy = 0;
      skill.cooldown = config.cooldown;
      skill.lastUsedTime = Date.now();
      
      if (config.manaCost) {
        this.onChessSpiritChange(-config.manaCost);
      }
      
      return { success: true, message: `${config.name}释放成功！` };
    }
    
    return effectResult;
  }

  // 执行技能效果
  private executeSkillEffect(
    skillType: SkillType, 
    targetPosition?: Position
  ): { success: boolean; message?: string } {
    switch (skillType) {
      case 'fireAttack':
        return this.executeFireAttack(targetPosition);
      case 'reinforcement':
        return this.executeReinforcement(targetPosition);
      case 'inspire':
        return this.executeInspire();
      default:
        return { success: false, message: '未知技能类型' };
    }
  }

  // 执行火攻技能
  private executeFireAttack(targetPosition?: Position): { success: boolean; message?: string } {
    if (!targetPosition) {
      return { success: false, message: '请选择目标位置' };
    }
    
    const effectId = this.generateId();
    const effect: SkillEffect = {
      id: effectId,
      type: 'fireAttack',
      startTime: Date.now(),
      duration: 5000, // 5秒持续时间
      position: targetPosition,
      radius: 2, // 影响半径
      damage: 20, // 每秒伤害
      onUpdate: (progress) => {
        // 这里可以添加火焰动画效果
        this.applyFireDamage(targetPosition, 2, 20 / 5); // 每0.2秒造成4点伤害
      },
      onComplete: () => {
        console.log('火攻效果结束');
      }
    };
    
    this.activeEffects.push(effect);
    return { success: true };
  }

  // 执行援军技能
  private executeReinforcement(targetPosition?: Position): { success: boolean; message?: string } {
    if (!targetPosition) {
      return { success: false, message: '请选择召唤位置' };
    }
    
    // 在目标位置周围召唤临时单位
    const positions = this.getReinforcementPositions(targetPosition);
    
    positions.forEach(pos => {
      this.onCreateTempUnit(pos, 15000); // 15秒临时单位
    });
    
    const effectId = this.generateId();
    const effect: SkillEffect = {
      id: effectId,
      type: 'reinforcement',
      startTime: Date.now(),
      duration: 15000, // 15秒
      onComplete: () => {
        console.log('援军效果结束');
      }
    };
    
    this.activeEffects.push(effect);
    return { success: true };
  }

  // 执行激将技能
  private executeInspire(): { success: boolean; message?: string } {
    // 为所有友军单位添加攻击力和攻击速度buff
    this.onApplyUnitBuff('inspire', 10000); // 10秒buff
    
    const effectId = this.generateId();
    const effect: SkillEffect = {
      id: effectId,
      type: 'inspire',
      startTime: Date.now(),
      duration: 10000, // 10秒
      onComplete: () => {
        console.log('激将效果结束');
      }
    };
    
    this.activeEffects.push(effect);
    return { success: true };
  }

  // 应用火焰伤害
  private applyFireDamage(center: Position, radius: number, damage: number): void {
    // 这个方法需要与敌军系统集成
    // 暂时只是占位符
    console.log(`在位置(${center.x}, ${center.y})半径${radius}范围内造成${damage}点火焰伤害`);
  }

  // 获取援军召唤位置
  private getReinforcementPositions(center: Position): Position[] {
    const positions: Position[] = [];
    const offsets = [
      { x: -1, y: 0 },
      { x: 1, y: 0 },
      { x: 0, y: -1 },
      { x: 0, y: 1 }
    ];
    
    offsets.forEach(offset => {
      positions.push({
        x: center.x + offset.x,
        y: center.y + offset.y
      });
    });
    
    return positions.filter(pos => 
      pos.x >= 0 && pos.x < 10 && pos.y >= 0 && pos.y < 9
    );
  }

  // 获取技能状态
  getSkillStatus(skillType: SkillType): {
    canUse: boolean;
    energyPercent: number;
    cooldownRemaining: number;
    reason?: string;
  } {
    const skill = this.skills[skillType];
    const config = SKILL_CONFIGS[skillType];
    
    const energyPercent = (skill.energy / skill.maxEnergy) * 100;
    const cooldownRemaining = Math.ceil(skill.cooldown / 1000);
    
    let canUse = true;
    let reason: string | undefined;
    
    if (skill.energy < skill.maxEnergy) {
      canUse = false;
      reason = '能量不足';
    } else if (skill.cooldown > 0) {
      canUse = false;
      reason = `冷却中 ${cooldownRemaining}秒`;
    }
    
    return {
      canUse,
      energyPercent,
      cooldownRemaining,
      reason
    };
  }

  // 获取所有技能状态
  getAllSkillsStatus(): Record<SkillType, ReturnType<typeof this.getSkillStatus>> {
    return {
      fireAttack: this.getSkillStatus('fireAttack'),
      reinforcement: this.getSkillStatus('reinforcement'),
      inspire: this.getSkillStatus('inspire')
    };
  }

  // 获取活跃效果
  getActiveEffects(): SkillEffect[] {
    return [...this.activeEffects];
  }

  // 强制增加技能能量（用于测试或特殊情况）
  addSkillEnergy(skillType: SkillType, amount: number): void {
    const skill = this.skills[skillType];
    skill.energy = Math.min(skill.maxEnergy, skill.energy + amount);
  }

  // 重置技能冷却（用于测试或特殊情况）
  resetSkillCooldown(skillType: SkillType): void {
    this.skills[skillType].cooldown = 0;
  }

  // 暂停/恢复技能系统
  setPaused(paused: boolean): void {
    if (paused) {
      // 暂停时记录当前时间
      this.lastUpdateTime = Date.now();
    } else {
      // 恢复时调整时间偏移
      const pauseDuration = Date.now() - this.lastUpdateTime;
      
      // 调整冷却时间
      Object.keys(this.skills).forEach(skillKey => {
        const skill = this.skills[skillKey as SkillType];
        if (skill.cooldown > 0) {
          skill.cooldown = Math.max(0, skill.cooldown - pauseDuration);
        }
      });
      
      // 调整效果时间
      this.activeEffects.forEach(effect => {
        effect.startTime += pauseDuration;
      });
      
      this.lastUpdateTime = Date.now();
    }
  }

  // 清理技能系统
  cleanup(): void {
    this.activeEffects = [];
    
    // 重置技能状态
    Object.keys(this.skills).forEach(skillKey => {
      const skill = this.skills[skillKey as SkillType];
      skill.energy = 0;
      skill.cooldown = 0;
      delete skill.lastUsedTime;
    });
  }

  // 生成唯一ID
  private generateId(): string {
    return Math.random().toString(36).substr(2, 9);
  }

  // 获取技能配置
  static getSkillConfig(skillType: SkillType): SkillConfig {
    return SKILL_CONFIGS[skillType];
  }

  // 获取所有技能配置
  static getAllSkillConfigs(): Record<SkillType, SkillConfig> {
    return { ...SKILL_CONFIGS };
  }
}